package com.carbeauty.service.impl;

import com.carbeauty.entity.Customer;
import com.carbeauty.repository.CustomerRepository;
import com.carbeauty.service.CustomerService;
import com.carbeauty.common.enums.BusinessStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 客户服务实现类
 * 
 * 实现客户管理的具体业务逻辑:
 * - 客户信息的增删改查
 * - 会员等级管理
 * - 余额和积分管理
 * - 消费记录更新
 * - 数据统计分析
 * 
 * @author CarBeauty Team
 */
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
    
    @Autowired
    private CustomerRepository customerRepository;
    
    // ==================== 基础CRUD操作 ====================
    
    @Override
    public Customer save(Customer customer) {
        // 如果是新客户，生成会员卡号
        if (customer.getId() == null) {
            customer.generateCardNo();
        }
        return customerRepository.save(customer);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<Customer> findById(Long id) {
        return customerRepository.findById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Customer getById(Long id) {
        return customerRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("客户不存在，ID: " + id));
    }
    
    @Override
    public void deleteById(Long id) {
        Customer customer = getById(id);
        customer.delete(); // 逻辑删除
        customerRepository.save(customer);
    }
    
    @Override
    public void deleteByIds(List<Long> ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
    
    // ==================== 查询操作 ====================
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> findAllActive() {
        return customerRepository.findByStatusOrderByCreateTimeDesc(BusinessStatus.ACTIVE);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<Customer> findAllActive(Pageable pageable) {
        // 这里需要创建一个支持分页的查询方法
        // 暂时使用基础的findAll方法
        return customerRepository.findAll(pageable);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<Customer> findByPhone(String phone) {
        return customerRepository.findByPhone(phone);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<Customer> findByCardNo(String cardNo) {
        return customerRepository.findByCardNo(cardNo);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> searchCustomers(String name, String phone, String carNumber, String memberLevel) {
        return customerRepository.findByConditions(name, phone, carNumber, memberLevel, BusinessStatus.ACTIVE);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<Customer> searchCustomers(String name, String phone, String carNumber, String memberLevel, Pageable pageable) {
        // 这里需要实现分页搜索，暂时返回基础分页
        return customerRepository.findAll(pageable);
    }
    
    // ==================== 会员管理 ====================
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> findByMemberLevel(String memberLevel) {
        return customerRepository.findByMemberLevelAndStatus(memberLevel, BusinessStatus.ACTIVE);
    }
    
    @Override
    public Customer upgradeMemberLevel(Long customerId, String newLevel) {
        Customer customer = getById(customerId);
        customer.setMemberLevel(newLevel);
        return customerRepository.save(customer);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Object[]> getMemberLevelStatistics() {
        return customerRepository.countByMemberLevel();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> findVipCustomers() {
        return customerRepository.findVipCustomers();
    }
    
    // ==================== 余额管理 ====================
    
    @Override
    public Customer recharge(Long customerId, BigDecimal amount, BigDecimal bonusAmount, 
                           Long operatorId, String paymentMethod) {
        Customer customer = getById(customerId);
        
        // 计算实际到账金额
        BigDecimal actualAmount = amount;
        if (bonusAmount != null && bonusAmount.compareTo(BigDecimal.ZERO) > 0) {
            actualAmount = actualAmount.add(bonusAmount);
        }
        
        // 增加余额
        customer.addBalance(actualAmount);
        
        // TODO: 创建充值记录
        // RechargeRecord record = new RechargeRecord(customerId, customer.getName(), customer.getPhone(), 
        //                                           amount, bonusAmount);
        // record.setOperatorId(operatorId);
        // record.setPaymentMethod(PaymentMethod.fromCode(paymentMethod));
        // rechargeRecordRepository.save(record);
        
        return customerRepository.save(customer);
    }
    
    @Override
    public Customer consume(Long customerId, BigDecimal amount) {
        Customer customer = getById(customerId);
        
        // 检查余额是否足够
        if (customer.getBalance().compareTo(amount) < 0) {
            throw new RuntimeException("客户余额不足，当前余额: " + customer.getBalance() + "，消费金额: " + amount);
        }
        
        // 扣减余额
        customer.deductBalance(amount);
        
        // 更新消费信息
        customer.updateConsumption(amount);
        
        return customerRepository.save(customer);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> findLowBalanceCustomers(BigDecimal threshold) {
        return customerRepository.findLowBalanceCustomers(threshold);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> getBalanceRanking(int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        return customerRepository.findByStatusOrderByBalanceDesc(BusinessStatus.ACTIVE);
    }
    
    // ==================== 积分管理 ====================
    
    @Override
    public Customer addPoints(Long customerId, Integer points) {
        Customer customer = getById(customerId);
        customer.addPoints(points);
        return customerRepository.save(customer);
    }
    
    @Override
    public Customer deductPoints(Long customerId, Integer points) {
        Customer customer = getById(customerId);
        if (!customer.deductPoints(points)) {
            throw new RuntimeException("客户积分不足，当前积分: " + customer.getPoints() + "，扣减积分: " + points);
        }
        return customerRepository.save(customer);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> getPointsRanking(int limit) {
        return customerRepository.findByStatusOrderByPointsDesc(BusinessStatus.ACTIVE);
    }
    
    // ==================== 消费统计 ====================
    
    @Override
    public Customer updateConsumption(Long customerId, BigDecimal consumptionAmount) {
        Customer customer = getById(customerId);
        customer.updateConsumption(consumptionAmount);
        return customerRepository.save(customer);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> getConsumptionRanking(int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        return customerRepository.findTopCustomersByConsumption(pageable);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> findHighValueCustomers(BigDecimal minConsumption) {
        return customerRepository.findByTotalConsumptionGreaterThanAndStatus(minConsumption, BusinessStatus.ACTIVE);
    }
    
    // ==================== 客户活跃度分析 ====================
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> findActiveCustomers() {
        LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
        return customerRepository.findActiveCustomers(thirtyDaysAgo);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Customer> findInactiveCustomers(int days) {
        LocalDateTime cutoffTime = LocalDateTime.now().minusDays(days);
        return customerRepository.findInactiveCustomers(cutoffTime);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Object getCustomerActivityStatistics() {
        // TODO: 实现客户活跃度统计
        return null;
    }
    
    // ==================== 数据统计 ====================
    
    @Override
    @Transactional(readOnly = true)
    public long getTotalCustomerCount() {
        return customerRepository.countByStatus(BusinessStatus.ACTIVE);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getTodayNewCustomerCount() {
        return customerRepository.countTodayNewCustomers();
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getThisMonthNewCustomerCount() {
        return customerRepository.countThisMonthNewCustomers();
    }
    
    @Override
    @Transactional(readOnly = true)
    public BigDecimal getTotalBalance() {
        BigDecimal total = customerRepository.sumTotalBalance();
        return total != null ? total : BigDecimal.ZERO;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Long getTotalPoints() {
        Long total = customerRepository.sumTotalPoints();
        return total != null ? total : 0L;
    }
    
    @Override
    @Transactional(readOnly = true)
    public BigDecimal getTotalConsumption() {
        BigDecimal total = customerRepository.sumTotalConsumption();
        return total != null ? total : BigDecimal.ZERO;
    }
    
    @Override
    @Transactional(readOnly = true)
    public BigDecimal getAverageConsumption() {
        BigDecimal avg = customerRepository.avgConsumption();
        return avg != null ? avg : BigDecimal.ZERO;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Object getCustomerStatistics() {
        // TODO: 实现客户综合统计
        return null;
    }
    
    // ==================== 数据验证 ====================
    
    @Override
    @Transactional(readOnly = true)
    public boolean isPhoneExists(String phone, Long excludeId) {
        Optional<Customer> customer = customerRepository.findByPhone(phone);
        if (customer.isPresent()) {
            return excludeId == null || !customer.get().getId().equals(excludeId);
        }
        return false;
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean isCardNoExists(String cardNo, Long excludeId) {
        Optional<Customer> customer = customerRepository.findByCardNo(cardNo);
        if (customer.isPresent()) {
            return excludeId == null || !customer.get().getId().equals(excludeId);
        }
        return false;
    }
    
    @Override
    public String generateUniqueCardNo() {
        String cardNo;
        do {
            // 生成会员卡号
            String date = java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
            String random = String.format("%04d", (int)(Math.random() * 10000));
            cardNo = "CB" + date + random;
        } while (customerRepository.existsByCardNo(cardNo));
        
        return cardNo;
    }
}
